package com.zzl.study.auth.security.repository;

import com.zzl.study.auth.security.authentication.context.Authentication;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.http.HttpCookie;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.web.server.context.ServerSecurityContextRepository;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author: zhangzl
 * @date: 2024/6/5 14:52
 * @version: 1.0
 * @description: 基于Redis存储的SecurityContextRepository
 */
@Slf4j
public class RedisServerSecurityContextRepository implements ServerSecurityContextRepository {

    /**
     * The default session attribute name to save and load the {@link SecurityContext}
     */
    public static final String DEFAULT_SPRING_SECURITY_CONTEXT_ATTR_NAME = "SPRING_SECURITY_CONTEXT";

    private String springSecurityContextAttrName = DEFAULT_SPRING_SECURITY_CONTEXT_ATTR_NAME;

    @Resource
    private ReactiveRedisTemplate<String, Authentication> authenticationRedisTemplate;

    @Override
    public Mono<Void> save(ServerWebExchange exchange, SecurityContext context) {
        String sessionId = resolveSessionId(exchange);
        if (!StringUtils.hasText(sessionId)) {
            return Mono.empty();
        }
        String cacheKey = this.springSecurityContextAttrName + ":" + sessionId;
        if (context == null) {
            return this.authenticationRedisTemplate.opsForValue().delete(cacheKey).flatMap(deleted -> Mono.empty());
        }
        OAuth2AuthenticationToken token = (OAuth2AuthenticationToken) context.getAuthentication();
        Authentication authentication = Authentication.of(token);
        return this.authenticationRedisTemplate.opsForValue().set(cacheKey, authentication).then();
    }

    @Override
    public Mono<SecurityContext> load(ServerWebExchange exchange) {
        String sessionId = resolveSessionId(exchange);
        if (!StringUtils.hasText(sessionId)) {
            return Mono.empty();
        }
        String cacheKey = this.springSecurityContextAttrName + ":" + sessionId;
        return this.authenticationRedisTemplate.opsForValue().get(cacheKey)
                .switchIfEmpty(Mono.empty())
                .flatMap(authentication -> {
                    OAuth2AuthenticationToken token = Authentication.to(authentication);
                    return Mono.just(new SecurityContextImpl(token));
                });
    }

    private String resolveSessionId(ServerWebExchange exchange) {
        MultiValueMap<String, HttpCookie> cookies = exchange.getRequest().getCookies();
        log.info("请求参数: {}", exchange.getRequest().getQueryParams());
        if (cookies.isEmpty() || !cookies.containsKey("SESSION")) {
            return null;
        }
        return cookies.getFirst("SESSION").getValue();
    }

}
